/*
 * @Author: HuangYue
 * @Date: 2022-04-08 11:38:17
 * @LastEditors: HuangYue
 * @LastEditTime: 2022-04-17 15:56:47
 * @FilePath: /graduation/src/pages/Admin/PeopleManagement/index.jsx
 * @Description:
 */
import { Popconfirm, Space, message, Drawer, Button, Divider } from 'antd';
import React, { useState, useRef } from 'react';
import ProTable from '@ant-design/pro-table';
import ProForm, {
  ProFormText,
  DrawerForm,
  ProFormRadio,
  ProFormCheckbox,
} from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import ProDescriptions from '@ant-design/pro-descriptions';
import { PlusOutlined } from '@ant-design/icons';
import { useModel } from 'umi';
import { getAllPeople, deletePeopleByUid, updatePeople, addPeople } from '../api/peopleManage';

const PeopleManagement = () => {
  const [allPeopleListDataSource, setAllPeopleListDataSoure] = useState([]);
  const [showDetail, setShowDetail] = useState(false); // 详情界面
  const [showDetailEditable, setShowDetailEditable] = useState(false); // 显示编辑界面
  const [createModalVisible, setModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState(undefined); // 当前行
  const formRef = useRef();
  const { initialState, setInitialState } = useModel('@@initialState');
  const { userInfo } = initialState;
  console.log('userInfo', userInfo);

  /**
   *  Delete node
   * @zh-CN 删除人员
   *
   * @param selectedRows
   */

  const handleRemove = async (selectedRows) => {
    console.log('selectedRows', selectedRows);
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      hide();
      const res = await deletePeopleByUid({ uid: selectedRows.uid });
      if (res.success) {
        setAllPeopleListDataSoure(res.data);
        message.success('成功删除 稍等一下刷新');
        return true;
      }
    } catch (error) {
      hide();
      message.error('删除失败 请重试');
      return false;
    }
  };
  const columns = [
    {
      dataIndex: 'avatar',
      title: '用户',
      valueType: 'avatar',
      width: 250,
      search: false,
      editable: false,
      render: (dom, record) => {
        return (
          <Space>
            {dom}
            <a
              onClick={() => {
                setCurrentRow(record);
                setShowDetail(true);
                setShowDetailEditable(false);
              }}
            >
              {record.nickName}
            </a>
          </Space>
        );
      },
    },
    {
      dataIndex: 'email',
      width: 250,
      search: false,
      title: '邮箱',
    },
    {
      dataIndex: 'phone',
      width: 200,
      title: '手机号',
    },
    {
      dataIndex: 'role',
      title: '角色',
      width: 200,
      align: 'center',
      filters: true,
      onFilter: true,
      search: false,
      valueEnum: {
        user: { text: '医院管理者' },
        engineer: { text: '工程师' },
      },
    },
    {
      dataIndex: 'status',
      title: '状态',
      width: 200,
      align: 'center',
      filters: true,
      onFilter: true,
      search: false,
      valueEnum: {
        Logout: { text: '注销', status: 'Default' },
        Approving: { text: '审核中', status: 'Processing' },
        Success: { text: '正常', status: 'Success' },
        Error: { text: '警告', status: 'Error' },
      },
    },
    {
      title: '操作',
      dataIndex: 'x',
      width: 200,
      valueType: 'option',
      fixed: 'right',
      search: false,
      render: (_, record) => {
        return [
          <a
            key="edit"
            onClick={() => {
              setCurrentRow(record);
              // setShowDetail(true);
              setShowDetailEditable(true);
            }}
          >
            编辑
          </a>,
          <Popconfirm
            key="confirm"
            title={`确认删除吗?`}
            okText="是"
            cancelText="否"
            onConfirm={async () => {
              await handleRemove(record);
            }}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];
  /**
   * 打开新增弹窗回调
   */
  const openAddDialog = (role) => {
    // 工程师已经加进来了，但是以何种形式添加呢？
    setCurrentRow({ ...currentRow, role: role });
    setShowDetailEditable(true);
  };
  return (
    <PageContainer
      header={{
        title: '人员管理',
        ghost: true,
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '管理页',
            },
            {
              path: '/admin/peopleManagement',
              breadcrumbName: '人员管理页面',
            },
          ],
        },
      }}
    >
      <ProTable
        columns={columns}
        request={getAllPeople}
        params={allPeopleListDataSource}
        // polling={2000}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              openAddDialog('user');
            }}
          >
            <PlusOutlined /> 添加医院管理者
          </Button>,
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              openAddDialog('engineer');
            }}
          >
            <PlusOutlined /> 添加工程师
          </Button>,
        ]}
        rowKey="uid"
        pagination={{
          showQuickJumper: true,
        }}
        search={true}
      />
      {/* 查看详情界面 */}
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
          setShowDetailEditable(false);
        }}
        closable={false}
      >
        {currentRow?.uid && (
          <ProDescriptions
            column={2}
            title={currentRow.realName}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.uid,
            }}
          >
            <ProDescriptions.Item span={2} dataIndex="avatar" label="头像" valueType={'avatar'} />
            <ProDescriptions.Item dataIndex="uid" label="uId" />
            <ProDescriptions.Item dataIndex="nickName" label="用户昵称" />
            <ProDescriptions.Item dataIndex="realName" label="真实姓名" />

            <ProDescriptions.Item dataIndex="idNumber" label="身份证号码" />
            <ProDescriptions.Item dataIndex="phone" label="电话" />
            <ProDescriptions.Item dataIndex="email" label="邮箱" />
            <ProDescriptions.Item
              dataIndex="role"
              label="角色"
              valueEnum={{
                user: { text: '医院管理者' },
                engineer: { text: '工程师' },
              }}
            />
            <ProDescriptions.Item
              dataIndex="status"
              label="账号状态"
              valueEnum={{
                Logout: { text: '注销', status: 'Default' },
                Approving: { text: '审核中', status: 'Processing' },
                Success: { text: '正常', status: 'Success' },
                Error: { text: '警告', status: 'Error' },
              }}
            />
            <ProDescriptions.Item
              dataIndex="permission"
              span={2}
              label="权限范围"
              render={(_, record) => {
                const { permission = [] } = record;
                return permission && permission.length > 0 ? permission.join('、') : '无';
              }}
            />
          </ProDescriptions>
        )}
      </Drawer>
      {/* 编辑界面 */}
      <DrawerForm
        visible={showDetailEditable}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => {
            setCurrentRow(undefined);
            setShowDetail(false);
            setShowDetailEditable(false);
          },
        }}
        closable="false"
        title={
          currentRow?.realName || `添加${currentRow?.role === 'admin' ? '医院管理者' : '工程师'}`
        }
        formRef={formRef}
        autoFocusFirstInput
        initialValues={currentRow}
        onFinish={async (values) => {
          if (formRef.current?.validateFields()) {
            try {
              if (currentRow.nickName) {
                const res = await updatePeople({ ...currentRow, ...values });
                if (res.success) {
                  message.success('编辑成功 请刷新下');
                  setAllPeopleListDataSoure(res.data);
                }
              } else {
                const res = await addPeople({ ...currentRow, ...values });
                if (res.success) {
                  message.success('提交成功 请刷新下');
                  setAllPeopleListDataSoure(res.data);
                }
              }
              setCurrentRow(undefined);
              setShowDetail(false);
              setShowDetailEditable(false);
              // 不返回不会关闭弹框
              return true;
            } catch (error) {
              message.error('提交失败 请重试');
            }
          }
        }}
      >
        <ProForm.Group>
          {/* <ProFormText name="uid" width="md" label="用户编号" disabled={true} allowClear={false} /> */}
          <ProFormText
            width="md"
            name="nickName"
            rules={[
              {
                required: true,
                message: 'Please input your nickname',
              },
            ]}
            label="用户昵称"
            placeholder="以Telemedicine-开头"
          />
          <ProFormText
            width="md"
            name="realName"
            rules={[
              {
                required: true,
                message: 'Please input your realName',
              },
            ]}
            label="用户真实姓名"
            placeholder="请输入真实姓名"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            width="md"
            name="email"
            rules={[
              {
                required: true,
                message: 'Please input your email',
              },
            ]}
            label="个人邮箱"
            placeholder="请输入个人邮箱"
          />
          <ProFormText
            width="md"
            name="phone"
            rules={[
              {
                required: true,
                message: 'Please input your phone',
              },
            ]}
            label="联系电话"
            placeholder="请输入联系电话"
          />
          <ProFormText
            width="lg"
            name="idNumber"
            rules={[
              {
                required: true,
                message: 'Please input your 身份证',
              },
            ]}
            label="身份证号码"
            placeholder="请输入联系身份证"
          />
        </ProForm.Group>
        <ProForm.Group>
          {/* <ProFormRadio.Group
            name="role"
            label="账号角色"
            rules={[
              {
                required: true,
                message: '请选择当前账号角色',
              },
            ]}
            options={[
              {
                label: '医院管理者',
                value: 'user',
              },
              {
                label: '工程师',
                value: 'engineer',
              },
            ]}
          /> */}
          <ProFormRadio.Group
            name="status"
            label="账号状态"
            rules={[
              {
                required: true,
                message: '请选择当前账号的状态',
              },
            ]}
            options={[
              {
                label: '注销',
                value: 'Logout',
              },
              {
                label: '审核中',
                value: 'Approving',
              },
              {
                label: '正常',
                value: 'Success',
              },
              {
                label: '警告',
                value: 'Error',
              },
            ]}
          />
          <ProFormCheckbox.Group
            name="permission"
            layout="horizontal"
            rules={[
              {
                required: true,
                message: '请赋予当前账号权限',
              },
            ]}
            label="权限"
            options={['权限1', '权限2', '权限3', '权限4']}
          />
        </ProForm.Group>
      </DrawerForm>
    </PageContainer>
  );
};

export default PeopleManagement;
